/*
 * Copyright @ 2025 weili23
 * com.example.ai 10:16
 * All right reserved.
 */

package com.example.ai;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @desc:
 * @author: weili23
 * @createTime: 2025/8/18 10:16
 * @version: v1.0
 */
@SpringBootTest
public class FilterSearch {
    public static final String INDEX_NAME = "person";

    @Resource
    private RestHighLevelClient  client;

    @Test
    void filterSearch() throws IOException {
        SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
        SearchSourceBuilder builder = new SearchSourceBuilder();

        //设置查询条件  查询name=曹操   而且 age !=18岁的
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery("name", "曹操"));
        boolQueryBuilder.mustNot(QueryBuilders.matchQuery("age", "18"));

        builder.query(boolQueryBuilder);
        searchRequest.source(builder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = search.getHits().getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsMap());
        }
    }
}
